const Controller = require('egg').Controller;
const path = require('path');
const fs = require('fs');
const awaitWriteStream = require('await-stream-ready').write;
const sendToWormhole = require('stream-wormhole');
const sd = require('silly-datetime');

class EditNoteController extends Controller {
    async echo() {
        const { ctx } = this

        let query = ctx.query.id
        const getData = await ctx.service.editNote.echo(query)
        await ctx.render('editNote.html', {
            data: getData
        })
    }

    async upNote() {
        const { ctx } = this
        const stream = await ctx.getFileStream();
        const filename = Math.random().toString(36).substr(2) + new Date().getTime() + path.extname(stream.filename).toLocaleLowerCase();
        const target = path.join(this.config.baseDir, 'app/public/uploads', filename);
        const writeStream = fs.createWriteStream(target);
        try {
            //异步把文件流 写入
            await awaitWriteStream(stream.pipe(writeStream));
        } catch (err) {
            //如果出现错误，关闭管道
            await sendToWormhole(stream);
            throw err;
        }

        let updatetimes = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
        let url = '/public/uploads/' + filename
        let data = stream.fields
        data.url = url
        data.time = updatetimes
        data.id = data.id.replace(/"/g, '')

        const getResult=await ctx.service.editNote.upNote(data)
        console.log(getResult)

        ctx.redirect('/')
    }
}

module.exports = EditNoteController;
